package fastServer;

import com.alibaba.fastjson.JSONObject;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import protocol.Header;
import protocol.IOMessage;
import protocol.MessageType;

public class HeartBeatRespHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		// TODO Auto-generated method stub
		if(evt instanceof IdleStateEvent){
			IdleStateEvent event = (IdleStateEvent) evt;
			switch(event.state()){
			
			case READER_IDLE:
				System.out.println("server read time out !!");
				break;
			case WRITER_IDLE:
				System.out.println("server write time out !!");
				break;
			case ALL_IDLE:
				ctx.close();
				break;
			default:
				break;
			}
		}
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg){
		
		IOMessage message = (IOMessage) msg;
		if(message.getHeader() != null && message.getHeader().getType()
				                       == MessageType.HEARTBEAT_REQ.value()){
			
			System.out.println("Receive client heart beat message : --> " + message);
			IOMessage heartBeat = buildHeartBeat();
			System.out.println("Send heart beat response message to client : --> " + heartBeat);
			
			ctx.writeAndFlush(heartBeat);
			
			System.out.println("!!!---ctx ----!!! --> " + ctx);
			
			ctx.fireChannelRead(msg);
		}else{
			ctx.fireChannelRead(msg);
		}
	}
	
	private IOMessage buildHeartBeat(){
		
		IOMessage message = new IOMessage();
		Header header = new Header();
		header.setType(MessageType.HEARTBEAT_RESP.value());
		message.setHeader(header);
		message.setBody(new JSONObject().toJSONString());
		
		return message;
	}
}
